package dws_fld

import (
	"fmt"
	"gorm.io/gorm"
	"server/global"
	"server/model/common/request"
)

type DwsFldService struct {
}


func (dwsFldService *DwsFldService) CreateDwsFld(dwsFld *DwsFld) (err error) {
	err = global.SysDB.Create(dwsFld).Error
	return err
}


func (dwsFldService *DwsFldService) DeleteDwsFld(dwsFld DwsFld) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&DwsFld{}).Where("id = ?", dwsFld.ID).Update("deleted_by", dwsFld.DeletedBy).Error; err != nil {
			return err
		}
		if err = tx.Delete(&dwsFld).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}


func (dwsFldService *DwsFldService) DeleteDwsFldByIds(ids request.IdsReq, deleted_by uint) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&DwsFld{}).Where("id in ?", ids.Ids).Update("deleted_by", deleted_by).Error; err != nil {
			return err
		}
		if err := tx.Where("id in ?", ids.Ids).Delete(&DwsFld{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}


func (dwsFldService *DwsFldService) DeleteDwsFldByCol(colName string, colVal any, delBy uint) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		sqlDel := fmt.Sprintf("%s=?", colName)
		if err := tx.Model(&DwsFld{}).Where(sqlDel, colVal).Update("deleted_by", delBy).Error; err != nil {
			return err
		}
		if err := tx.Where(sqlDel, colVal).Delete(&DwsFld{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}


func (dwsFldService *DwsFldService) UpdateDwsFld(dwsFld DwsFld) (err error) {
	err = global.SysDB.Save(&dwsFld).Error
	return err
}


func (dwsFldService *DwsFldService) GetDwsFldById(id uint) (dwsFld DwsFld, err error) {
	err = global.SysDB.Where("id = ?", id).First(&dwsFld).Error
	return
}


func (dwsFldService *DwsFldService) GetDwsFldByCol(colName string, colVal any) (dwsFlds []DwsFld, err error) {
	sqlFind := fmt.Sprintf("%s=?", colName)
	err = global.SysDB.Where(sqlFind, colVal).Find(&dwsFlds).Error
	return
}


func (dwsFldService *DwsFldService) GetDwsFldInfoList(info DwsFldSearch) (list []DwsFld, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.SysDB.Model(&DwsFld{})
	var dwsFlds []DwsFld
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.SrcTbId >= 0 {
		db = db.Where("dwsTbId = ?", info.SrcTbId)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Find(&dwsFlds).Error
	return dwsFlds, total, err
}


func (dwsFldService *DwsFldService) GetAllDwsFlds() (dwsFld []DwsFld, err error) {
	err = global.SysDB.Find(&dwsFld).Error
	return dwsFld, err
}


func (dwsFldService *DwsFldService) GetDwsFld() (dwsFld []DwsFld, err error) {
	err = global.SysDB.Find(&dwsFld).Error
	return dwsFld, err
}
